package com.dy.树.中序遍历;

import com.dy.树.TreeNode;
import sun.reflect.generics.tree.Tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

//左中右
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root==null){
            return res;
        }
        getTraversal(root.left,res);
        res.add(root.val);
        getTraversal(root.right,res);
        return res;
    }
    public void getTraversal(TreeNode root,List<Integer> list){
        if(root!=null){
            getTraversal(root.left,list);
            list.add(root.val);
            getTraversal(root.right,list);
        }
    }

    //迭代
    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root==null){
            return res;
        }
        Stack<TreeNode> stack =new Stack<>();
        TreeNode p = root;
        while(p!=null ||!stack.isEmpty()){
            while(p!=null){
                stack.push(p);
                p=p.left;
            }
            p=stack.pop();
            res.add(p.val);
            p=p.right;
        }
        return res;
    }
}
